package org.carabiner.infinitest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class ProcessCommunicator
{
  private ServerSocket serverSocket;

  public ProcessCommunicator()
  {
    try
    {
      serverSocket = new ServerSocket(0);
    }
    catch (IOException e)
    {
      throw new RuntimeException("Cannot open port for interprocess communication", e);
    }
  }

  public int getPort()
  {
    return serverSocket.getLocalPort();
  }

  public Object getResults()
  {
    try
    {
      Socket socket = serverSocket.accept();
      ObjectInputStream oiStream = new ObjectInputStream(socket.getInputStream());
      Object results = oiStream.readObject();
      oiStream.close();
      socket.close();
      return results;
    }
    catch (IOException e)
    {
      throw new RuntimeException("Error reading from socket", e);
    }
    catch (ClassNotFoundException e)
    {
      throw new RuntimeException("Error processing results (inconsistent compliation?)", e);
    }
  }
}
